<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchDialog"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getListNew"
        :otherParams="{
          planCode: '',
          prodCode: '',
          prodOrderType: '',
        }"
        uniqueId="mesPrintProdOrder"
      ></ele-page>
    </div>
    <ele-form-drawer
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
    </ele-form-drawer>

    <!-- 容量码模态框 -->
    <barcodePrintingAddModel
      ref="barcodePrintingAddModel"
      @preview="printCodePreview"
      @clearCode="clearCode"
      :title="modelTitle"
      @refreshList="getListArr()"
    ></barcodePrintingAddModel>

    <!-- 清除容量码模态框 -->
    <barcodePrintingClearModel
      ref="barcodePrintingClearModel"
      :title="clearModelTitle"
      @refreshList="getListArr()"
    ></barcodePrintingClearModel>
    <!-- 补打模态框 -->
    <repairPrintModel
      ref="repairPrintModel"
      @refreshList="getListArr()"
    ></repairPrintModel>
    <PrintPreview
      ref="printPreview"
      @close="previewClose"
      @ok="previewOk"
      :printInfo="printInfo"
    ></PrintPreview>
    <!-- 生码 -->
    <el-drawer
      :title="createTitle"
      :visible.sync="createVisible"
      :append-to-body="true"
      @close="clearCreateDialog()"
      v-loading="loading"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      size="60%"
    >
      <div style="padding: 20px;">
        <ele-form
          v-model="createData"
          v-bind="createFormConfig"
          ref="form"
        ></ele-form>
        <ele-table-editor
          ref="table-editor"
          :isShowAdd="false"
          :isShowDelete="false"
          :columns="columns"
          v-model="capacityTableForm"
        >
          <!-- 容量 -->
          <template v-slot:count="{ data }">
            <el-input-number
              v-model="data.count"
              :precision="4"
              :min="0.0001"
            ></el-input-number>
          </template>

          <!-- 数值 -->
          <template v-slot:amount="{ data }">
            <el-input-number
              v-model="data.amount"
              :precision="0"
              :min="1"
            ></el-input-number>
          </template>

          <!-- 分类操作 -->
          <template v-slot:operate="{ data, index }">
            <el-button type="text" @click="handleCopyRow(data)">{{
              $i18n.t("common.copy")
            }}</el-button>
            <el-divider
              direction="vertical"
              v-if="capacityTableForm.length > 1"
            ></el-divider>
            <el-button
              v-if="capacityTableForm.length > 1"
              type="text"
              @click="handleDelRow(index)"
              >{{ $i18n.t("common.delete") }}</el-button
            >
          </template>
        </ele-table-editor>
        <div slot="footer" class="dialog-footer">
          <el-button @click="clearCreateDialog()">
            {{ $t("common.cancel") }}
          </el-button>
          <el-button type="primary" @click="() => handleCreate()">
            {{ $t("wmsReceivePrint.create") }}
          </el-button>
          <el-button type="primary" @click="() => handleCreate(true)">{{
            $i18n.t("mesCapacityCodePrinting.createPrint")
          }}</el-button>
        </div>
      </div>
    </el-drawer>
    <templateSelect
      ref="templateSelect"
      v-model="createData.barcodePrintTempCode"
      :searchData="{
        goodsCode: createData.goodsCode,
        businessTypeCode: businessTypeMap[createData.printSort],
      }"
      @select="getTempCode"
    ></templateSelect>
    <repairPrintTable ref="repairPrintTables"></repairPrintTable>
  </div>
</template>

<script>
import { operateList, searchConfig, formDescDialog } from "./config";
import templateSelect from "@/components/templateSelect/index.vue";
import {
  getList,
  getListNew,
  rowCreate,
  rowUpdate,
  rowDel,
  getInfo,
  getProdOrderStatusList,
  getPrepositionTypeList,
} from "@/api/print/mesCapacityCode";

import {
  genCodeBatch, //批量生码
  // clearBoxcode,
  // selectListByConfigurationCode,
  getCapacityCodeList,
  checkCapacityCode, //校验是否已经生成对应类型容量码
  templateType, //获取生码分类
  getProdByOrder, //根据订单获取型号
  selectCommonProduceRelByProduce, //根据型号、分类获取生码规则接口
  selectListByConfigurationCode, //校验容量码补打是否需要审核
} from "@/api/print/mesCapacityCode";
import PrintPreview from "./components/printPreview.vue";
import barcodePrintingAddModel from "./components/barcodePrintingAddModel";
import barcodePrintingClearModel from "./components/barcodePrintingClearModel";

import { popover } from "@/utils/judge";

import repairPrintModel from "./components/repairPrintModel.vue";
import repairPrintTable from "./components/repairPrintTable.vue";
import EleTableEditor from "ele-table-editor";
import { getDict } from "@/api/common";

export default {
  name: "mesCapacityCodePrinting",
  components: {
    barcodePrintingAddModel,
    barcodePrintingClearModel,
    repairPrintModel,
    repairPrintTable,
    EleTableEditor,
    templateSelect,
    PrintPreview,
  },
  mixins: [searchConfig],
  data() {
    const _this = this;
    return {
      printInfo: { form: {}, list: [] },
      businessTypeMap: {
        box_code: "PRINT_MES_PC_PACKAGEING_BOX_CODE",
        pack_code: "PRINT_MES_PC_INNER_PACKING_BOX_CODE",
        tray_code: "PRINT_MES_PC_PALLET_CODE",
      },
      capacityTableForm: [{}],
      // 校检规则
      rules: {
        capacity: [
          {
            required: true,
            message: $i18n.t("mesCapacityCodePrinting.requiredCapacity"),
          },
        ],
        volume: {
          required: true,
          message: $i18n.t("mesCapacityCodePrinting.quantityRequired"),
        },
      },

      // 容量表格
      columns: [
        {
          // el-table-column 的属性
          type: "index",
        },
        {
          // el-table-column 的属性
          prop: "count",
          label: $i18n.t("mesCapacityCodePrinting.volume"), //"容量",
          // 支持 显示隐藏
          vif: true,
        },
        {
          prop: "amount",
          label: $i18n.t("mesCapacityCodePrinting.amount"), // "数量",
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"), //"操作",
          width: 120,
          algin: "center",
          fixed: "right",
          content: {
            style: {
              textAlign: "center",
            },
          },
        },
      ],

      modelTitle: "",
      clearModelTitle: "",
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      formDescDialog, //新增修改框
      // searchConfig,
      operateList,
      getListNew,
      createTitle: _this.$i18n.t("mesCapacityCodePrinting.create"),
      createVisible: false,
      maxNum: 9999,
      createData: {
        orderCode: null,
        goodsCode: null,
        printSort: null,
        codeStrategy: null,
        productType: null,
        selTemplateDisabled: false,
      },
      goodsCodeList: [],
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
          fixed: "left",
        },
        {
          prop: "planCode",
          label: $i18n.t("mesCapacityCodePrinting.planCode"),
          fixed: "left",
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "orderCode",
          label: $i18n.t("mesCapacityCodePrinting.orderCode"),
          fixed: "left",
          minWidth: 240,
          render: (h, scope) => {
            return popover(scope.row.orderCode, h, "", () =>
              _this.goChild({ orderCode: scope.row.orderCode })
            );
          },
        },

        {
          prop: "prodCode",
          label: $i18n.t("mesCapacityCodePrinting.prodCode"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesCapacityCodePrinting.prodName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "quantity",
          label: $i18n.t("mesCapacityCodePrinting.planQuantity"),
          minWidth: 110,
          showOverflowTooltip: true,
        },
        {
          prop: "actualQuantity",
          label: $i18n.t("mesCapacityCodePrinting.actualQuantity"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "orderStatus",
          label: $i18n.t("mesCapacityCodePrinting.orderStatus"),
          minWidth: 140,
          showOverflowTooltip: true,
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getProdOrderStatusList();
            return list.data.result;
          },
        },

        {
          prop: "planBeginDate",
          label: $i18n.t("mesCapacityCodePrinting.planBeginDate"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "workshopName",
          label: $i18n.t("common.workshopName"),
          width: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "lineName",
          label: $i18n.t("common.lineName"),
          width: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "unit",
          label: $i18n.t("mesCapacityCodePrinting.measureUnit"),
          minWidth: 110,
          showOverflowTooltip: true,
        },
      ],
      createFormConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: "right",
        formDesc: {
          orderCode: {
            //生产工单编码
            type: "input",
            label: _this.$i18n.t("mesCapacityCodePrinting.orderCode"),
            layout: 12,
            disabled: true,
          },
          unit: {
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.unit"),
            layout: 12,
            disabled: true,
          },
          printSort: {
            // 生码类型
            type: "select",
            label: _this.$i18n.t("mesCapacityCodePrinting.printSort"),
            layout: 12,
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const list = await getDict("template_type_capacitycode");
              return list.data.result;
            },
            on: {
              change(val) {
                let createData = _this.createData;
                const params = {
                  goodsCode: createData.goodsCode,
                  templateType: val,
                  type: "codeStrategy",
                };
                selectCommonProduceRelByProduce(params).then((res) => {
                  _this.createFormConfig.formDesc.codeStrategy.options =
                    res.data.result;
                  _this.createData.codeStrategy = null;
                  if (createData.goodsCode && createData.printSort) {
                    _this.getRuleAndTemplate();
                  }
                });
              },
            },
            required: true,
            disabled: false,
          },
          goodsCode: {
            // 物料
            type: "select",
            label: _this.$i18n.t("mesCapacityCodePrinting.goodsCode"),
            layout: 12,
            prop: {
              value: "prodCode",
              text: "prodName",
            },
            options: async (data) => {
              const params = {
                orderCode: data.orderCode,
              };
              const list = await getProdByOrder(params);
              _this.goodsCodeList = list.data.result;
              return list.data.result;
            },
            on: {
              async change(val) {
                let createData = _this.createData;
                let goodsCodeList = _this.goodsCodeList;
                let goodsCode = goodsCodeList.find((item) => {
                  return item.prodCode == val;
                });
                if (goodsCode) {
                  _this.createData.productType = goodsCode.productType;
                }
                const params = {
                  goodsCode: val,
                  templateType: createData.printSort,
                  type: "codeStrategy",
                };
                selectCommonProduceRelByProduce(params).then((res) => {
                  _this.createFormConfig.formDesc.codeStrategy.options =
                    res.data.result;
                  _this.createData.codeStrategy = null;
                  if (createData.goodsCode && createData.printSort) {
                    _this.getRuleAndTemplate();
                  }
                });
              },
            },
            required: true,
            disabled: false,
          },

          codeStrategy: {
            // 编码规则
            type: "select",
            label: _this.$i18n.t("mesCapacityCodePrinting.codeStrategy"),
            layout: 12,
            prop: {
              value: "codeStrategyCode",
              text: "codeStrategyDescription",
            },
            options: async (data) => {
              const params = {
                goodsCode: data.goodsCode,
                templateType: data.printSort,
                type: "codeStrategy",
              };
              const list = await selectCommonProduceRelByProduce(params);
              return list.data.result;
            },
            on: {
              change(val) {
                const item = _this.createFormConfig.formDesc.codeStrategy.options.find(
                  (x) => x.codeStrategyCode === val
                );
                _this.$set(
                  _this.createData,
                  "codeStrategyName",
                  item.codeStrategyDescription
                );
              },
            },
            required: true,
            disabled: false,
          },
          barcodePrintTemp: {
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.labelTemplate"),
            required: false,
            layout: 12,
            disabled: (data) => {
              return data.selTemplateDisabled;
            },
            attrs: {
              readonly: true,
            },
            slots: {
              append(h) {
                return (
                  <el-button
                    icon="el-icon-search"
                    disabled={_this.createData.selTemplateDisabled}
                    onClick={() => {
                      _this.$refs.templateSelect.show();
                    }}
                  ></el-button>
                );
              },
            },
          },
        },
      },
      selected: [],
    };
  },

  computed: {},
  methods: {
    clearCode() {
      this.clearBarcode(this.selected[0]);
    },
    // 组装预览数据
    printCodePreview(form, list) {
      this.printInfo = {
        form: form,
        list: list,
      };
      this.$refs.printPreview.visible = true;
    },
    // 预览弹窗确定
    previewOk() {
      this.clearCreateDialog();
      this.refresh();
    },
    // 预览弹窗取消
    previewClose() {},
    clearFormDialog() {
      this.innerVisible = false;
      this.form.amount = 0;
      this.maxnum = 9999;
    },

    setBarcodePrintTempRequired(bool = false) {
      this.$set(
        this.createFormConfig.formDesc.barcodePrintTemp,
        "required",
        bool
      );
    },
    getTempCode(data) {
      this.$set(this.createData, "barcodePrintTemp", data.name);
      this.$set(this.createData, "barcodePrintTempCode", data.code);
    },
    getCodeStrategy(data) {
      this.$set(this.createData, "codeStrategy", data.code);
      this.$set(this.createData, "codeStrategyName", data.name);
    },
    sortChange() {
      console.log(this);
    },
    openCreateDialog(row) {
      console.log(row);
    },
    //复制一行容量数据
    handleCopyRow(data) {
      this.$nextTick(() => {
        let copyData = Object.assign({}, JSON.parse(JSON.stringify(data)));
        delete copyData.id;
        this.capacityTableForm.push(copyData);
      });
    },
    //移除一行容量数据
    handleDelRow(idx) {
      this.$nextTick(() => {
        this.capacityTableForm.splice(idx, 1);
      });
    },
    getListArr() {
      this.refresh(false);
    },
    //表格顶部按钮操作事件
    handleOperateEvent({ handleName, name, rows }) {
      this.title = name;
      let _this = this;
      this.selected = rows;
      const fnc = {
        add: () => {
          this.changeMaster(false);
          this.formDataDialog = {};
          this.visible = true;
        },
        // delete: () => {
        //   this.$confirm("此操作将删除该生产工单, 是否继续?", "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }).then(() => {
        //     const ids = rows.map((val) => val.id).join(",");
        //     this.rowDel(ids);
        //   });
        // },
        // 点击生码按钮
        getGenCount() {
          _this.showCreate(rows[0]);
        },

        // 点击生码按钮
        getGenCountNext() {
          _this.showCreateNext(rows[0]);
        },

        capacityCode: () => {
          // 打印容量码
          this.modelTitle = name;
          this.$refs.barcodePrintingAddModel.init({
            ...rows[0],
          });
        },
        // 清除容量码
        clearBarcode() {
          _this.clearBarcode(rows[0]);
        },
        repairPrint: async () => {
          console.log("jinru补打", rows[0]);
          let { workshopCode, lineCode, orderCode, barcodePrintTemp } = rows[0];
          let data = {
            configurationCode: "com_capacity_code_reviewed",
            levelType: "4",
            workshopCode: workshopCode,
          };

          this.loading = true;
          let res = await selectListByConfigurationCode(data);
          let { result } = res.data;
          this.loading = false;
          let bool = false; //true 需要审核  false 不需要审核
          if (result && result.length) {
            if (result[0].value == "1") {
              bool = true;
            }
          }
          if (bool) {
            this.$refs.repairPrintTables.init({
              ...rows[0],
              isPrint: 0,
            });
          } else {
            // 补打已打印容量码
            this.$refs.repairPrintModel.init({
              ...rows[0],
              barcodePrintTemp: rows[0].barcodePrintTemp,
              quantity: 0,
              type: 2, //不需要审批
            });
          }
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        show: () => {
          // 查看详情，并打开界面
          this.editInfo(row.id, true);
        },
        edit: () => {
          // 修改详情，并打开界面
          this.editInfo(row.id, false);
        },
        multiAdd: () => {
          this.goMultiAdd({ id: row.id });
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return; // 判断状态
      this.isLoading = true;
      this.formDataDialog.id ? this.rowUpdate(data) : this.rowCreate(data);
    },
    //新增
    rowCreate(data) {
      rowCreate(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(
            message || $i18n.t("common.addSuccess")
          );
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    // 修改详情
    editInfo(id, flag) {
      this.changeMaster(flag);
      this.loading = true;
      getInfo(id)
        .then((res) => {
          this.formDataDialog = res.data.result;
          this.visible = true;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //修改
    rowUpdate(data) {
      rowUpdate(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(
            message || $i18n.t("common.editSuccess")
          );
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(
            message || $i18n.t("common.deleteSuccess")
          );
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
    //跳转至子页面
    goChild(queryParam) {
      let pathParam = "/print/mesCapacityCode";
      this.$router.push({ path: pathParam, query: queryParam });
    },
    // 跳转至批量新增页面
    goMultiAdd(queryParam) {
      let pathParam = "/print/mesProdOrderAdd";
      this.$router.push({ path: pathParam, query: queryParam });
    },
    changeMaster(flag) {
      if (flag) {
        formDescDialog.disabled = true;
        formDescDialog.isShowSubmitBtn = false;
      } else {
        formDescDialog.disabled = false;
        formDescDialog.isShowSubmitBtn = true;
      }
    },
    clearCreateDialog() {
      this.createVisible = false;
      this.capacityTableForm = [{}];
      this.createData.orderCode = null;
      this.createData.goodsCode = null;
      this.createData.printSort = null;
      this.createData.codeStrategy = null;
      this.createData.barcodePrintTemp = null;
      this.createData.selTemplateDisabled = false;
      this.createData.barcodePrintTempCode = null;
      this.createFormConfig.formDesc.codeStrategy.disabled = false;
      this.printInfo = { form: {}, list: [] };
      this.$refs.printPreview.visible = false;
      this.$refs.barcodePrintingClearModel.visible = false;
      this.$refs.barcodePrintingAddModel.visible = false;
    },
    showCreate(data) {
      this.createVisible = true;
      this.createData.orderCode = data.orderCode;
      this.createData.unit = data.unit;
    },
    showCreateNext(data) {
      setTimeout(() => {
        this.createVisible = true;
        this.createData.orderCode = data.orderCode;
        this.createData.printSort = data.capacityType;
        this.createData.goodsCode = data.prodCode;
        this.createData.productType = data.productType;
      }, 500);
    },
    // 查询一下是否已经生过码，如果生过码就用以前的编码规则和模板
    async getRuleAndTemplate() {
      let check = {
        orderCode: this.createData.orderCode,
        prodCode: this.createData.goodsCode,
        productType: this.createData.productType,
        capacityType: this.createData.printSort,
      };
      const codeListRes = await getCapacityCodeList(check);
      const { result } = codeListRes.data;
      this.createFormConfig.formDesc.codeStrategy.disabled = !!result.codeStrategy;
      this.createData.selTemplateDisabled = !!result.barcodePrintTempCode;
      if (result.barcodePrintTempCode) {
        this.getTempCode({
          name: result.barcodePrintTemp || "",
          code: result.barcodePrintTempCode || "",
        });
      }
      if (result.codeStrategy) {
        this.getCodeStrategy({
          name: result.codeStrategyName || "",
          code: result.codeStrategy || "",
        });
      }
    },
    handleCreate(print) {
      this.setBarcodePrintTempRequired(print);
      // 等待追加模板是否必填
      setTimeout(() => {
        this.$refs.form.validate().then((valid) => {
          if (!valid) {
            let capacityTableForm = this.capacityTableForm;
            console.log(capacityTableForm);
            let data = [];
            let result = false;
            capacityTableForm.forEach((item, index) => {
              let idx = index + 1;
              if (!isFinite(item.amount)) {
                setTimeout(() => {
                  this.$message.error($i18n.t("capacityCode.msg1", { idx }));
                }, 10);
                result = true;
              }
              if (!isFinite(item.count)) {
                setTimeout(() => {
                  this.$message.error($i18n.t("capacityCode.msg2", { idx }));
                }, 10);
                result = true;
              }
              data.push({
                orderCode: this.createData.orderCode,
                prodCode: this.createData.goodsCode,
                capacityType: this.createData.printSort,
                codeStrategy: this.createData.codeStrategy,
                codeStrategyName: this.createData.codeStrategyName,
                productType: this.createData.productType,
                amount: item.amount,
                count: item.count,
              });
            });
            if (!result) {
              this.loading = true;
              genCodeBatch(data)
                .then(async (res) => {
                  if (res.data.success) {
                    const message = res.data.message;

                    // 打印页面
                    if (print) {
                      let check = {
                        orderCode: this.createData.orderCode,
                        prodCode: this.createData.goodsCode,
                        productType: this.createData.productType,
                        capacityType: this.createData.printSort,
                      };
                      const codeListRes = await getCapacityCodeList(check);
                      const { success, result } = codeListRes.data;
                      if (success) {
                        let tableData = result.barCodeResult;
                        tableData.forEach((item) => {
                          item.amount =
                            parseInt(item.sumCodeNum) -
                            parseInt(item.hasPrintNum);
                          item.unPrintNum =
                            parseInt(item.sumCodeNum) -
                            parseInt(item.hasPrintNum);
                        });
                        // 打印
                        this.printCodePreview(this.createData, tableData);
                      }
                      return;
                    }

                    this.$message.success(
                      message || this.$i18n.t("mesCapacityCodePrinting.createSuccess")
                    );

                    this.clearCreateDialog();
                    this.refresh();
                  } else {
                    this.$message.warning(res.data.message);
                  }
                })
                .finally(() => {
                  this.loading = false;
                });
            }
          }
        });
      }, 0);
    },

    async clearBarcode(data) {
      this.clearModelTitle = this.$i18n.t("mesCapacityCodePrinting.clearCapacityCode");
      this.$refs.barcodePrintingClearModel.init({
        ...data,
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  padding: 20px;
  display: flex;
  justify-content: end;
}
</style>
